package com.yswy.domain.common.util;

import com.alibaba.nacos.client.utils.StringUtils;
import com.auth0.jwt.interfaces.Claim;
import com.yswy.domain.entity.AppUser;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * token工具类
 */
public class TokenUtils {

    public static AppUser getUser(HttpServletRequest request) {

        AppUser user = (AppUser) request.getSession().getAttribute("user");
        return user;
    }

    public static Long getUserId(HttpServletRequest request) {
        if (getUser(request) != null){
            return getUser(request).getId();
        }else {
            return  null ;
        }
    }


    public static String getUserPhone(HttpServletRequest request) {
        if (getUser(request) != null){
            return getUser(request).getUserPhone();
        }else {
            return  null ;
        }

    }

    public static String getTokenToken(HttpServletRequest request) {
        String Authorization = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(Authorization)){


            return Authorization;
        }else {
            return  null ;
        }
    }

    public static String getChannle(HttpServletRequest request) {
        String channle = request.getHeader("channle");
        if (StringUtils.isNotEmpty(channle)){
            return channle;
        }else {
            return  "android" ;
        }
    }
    public static String getVersion(HttpServletRequest request) {
        String version = request.getHeader("version");
        if (StringUtils.isNotEmpty(version)){
            return version;
        }else {
            return  null ;
        }
    }

    /***
     * 获取客户端ip地址
     * @param request
     */
    public static String getIP(final HttpServletRequest request) {
        String ipStr = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
            ipStr = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
            ipStr = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
            ipStr = request.getRemoteAddr();
        }

        // 多个路由时，取第一个非unknown的ip
        final String[] arr = ipStr.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ipStr = str;
                break;
            }
        }
        //目的是将localhost访问对应的ip 0:0:0:0:0:0:0:1 转成 127.0.0.1。
        return ipStr.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ipStr;
    }
}
